package com.cz.zslu.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cz.zslu.common.DateUtil;
import com.cz.zslu.common.ReturnObject;
import com.cz.zslu.entity.SysUser;
import com.cz.zslu.entity.ZslOrder;
import com.cz.zslu.entity.ZslStoreCommodity;
import com.cz.zslu.interceptor.BaseContextHandler;
import com.cz.zslu.interceptor.IgnoreAuth;
import com.cz.zslu.rest.BaseController;
import com.cz.zslu.service.ISysUserService;
import com.cz.zslu.service.IZslOrderService;
import com.cz.zslu.service.IZslStoreCommodityService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 商品管理 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/pay")
@Api(description = "支付接口")
public class PayController extends BaseController<IZslStoreCommodityService, ZslStoreCommodity> {

    @Autowired
    private IZslOrderService iZslOrderService;
    @Autowired
    private ISysUserService iSysUserService;

    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public static String app_id = "2018111362159106";

    // 商户私钥，您的PKCS8格式RSA2私钥
    public static String merchant_private_key =
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDX6q7KIGmx5LT8WLoHUL2NDTrHZEDooYwAhQoyttTaDkTz9NgvoyUqrxib74xliEmKABQIVTzDhiP8sIb+RMdYhNlpv+IBeUWHW0Hni2kW+YdvSHz4P4j8WLSZkDm5WJOYFogCRr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dePhpT+GHTMc/hP/8xLyx3QKBgC/uaRpXDqm79CPEhbXS5b5VSfcNZgQySKRS5wWzGFxb7M0+5E6B8hh51HWjV4SwGdFx+lSZr9WEcGIDM5EJM8hBie5H2e1/4lllSGn8cnhGj1JcRC31kP4WiXJtzZNZo2S/S6DXnq5bVQFPCb+bT1TnI9ZvIXQlSZWvmkg6hrZ1AoGAQDy+TKQq0ipEALfV3hyd1DnpLW7vszLm2an/mrV/mnlBUOieX72sB39vLqgXSChBTLyuLhpxChfJ+b2VBRW/ycWFWNJlwGe69R1ARiolR+XnHmY+YU8pEwFKaIXZRlv5IpPg8pBBZCHQO6e8OUaQmBxZH/Idj8zkYFc9ggwLQLs=";

    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoNU9WThD8jnylD6lEZqFKGoHX" +
            "+NNakPBsJgNof1Y6IjRAKSRyFewN6W252JPinKGsIB3oARp1o8fKe1yEYmTlcuA2zc3FpDOeKpZQDM9L58qegjDoY8opYPlKRCZ6jUahC5vQ8VPwDu7P2oEAIoeKGcMAggHVRwS9DBBtsY+q7aJp+4bI5Zi4tPV6WlDM2dSZpcm+GXDYQ4JRII0R9a4pTI+51kIVVPecXnYhZxGmZhIRQvCd9T2I3OYFxuHeWnrxoyw6B1UnY69l9RlDXvVXcGO9KGOp332XksVwJEbJ1q/5uKcvAkJgGu/KLoVGyiziBCeZc8Bq+I/MwVIgEDLTwIDAQAB";
    // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String notify_url = "http://www.ziselu.com/zslapi/pay/callBack";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String return_url = "http://www.ziselu.com/purple_heron_merchants/page/business.html";

    // 签名方式
    public static String sign_type = "RSA2";

    // 字符编码格式
    public static String charset = "utf-8";

    // 支付宝网关
    public static String gatewayUrl = "https://openapi.alipay.com/gateway.do";


    @ApiOperation("加盟支付")
    @RequestMapping(value = "/affiliatePay", method = RequestMethod.POST)
    public ReturnObject affiliatePay(@ApiParam("金额") BigDecimal amount, @ApiParam("类型（1：一年，2：2年）") Long type) throws AlipayApiException {
        ZslOrder zslOrder = new ZslOrder(null, null, 0,1, BaseContextHandler.getUserID(), null
                , BigDecimal.valueOf(0), amount, 1,
                type.toString(), null, null, null, null, null, null, null,
                null, "加盟", 1, null, null);
        iZslOrderService.insert(zslOrder);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset
                , alipay_public_key, sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = zslOrder.getId().toString();
        //付款金额，必填
        String total_amount = zslOrder.getTotalPrice().toString();
        //订单名称，必填
        String subject = zslOrder.getName();
        //商品描述，可空
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return new ReturnObject<>(0, "获取成功", result);
    }

    @IgnoreAuth
    @ApiOperation("支付接口")
    @RequestMapping(value = "/payment", method = RequestMethod.POST)
    public ReturnObject payment(@ApiParam("订单id") Long id) throws AlipayApiException {
        ZslOrder order = iZslOrderService.selectById(id);
        if (order.getState() != 1) {
            return new ReturnObject<>(1, "订单异常无法支付");
        }
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json", charset
                , alipay_public_key, sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        ZslOrder zslOrder = iZslOrderService.selectById(id);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = id.toString();
        //付款金额，必填
        String total_amount = zslOrder.getTotalPrice().toString();
        //订单名称，必填
        String subject = zslOrder.getName();
        //商品描述，可空
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return new ReturnObject<>(0, "获取成功", result);
    }


    @IgnoreAuth
    @ApiOperation("支付回调")
    @RequestMapping(value = "/callBack", method = RequestMethod.POST)
    public String callBack(HttpServletRequest request, HttpServletResponse
            response) throws IOException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = Maps.newHashMap();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, charset, sign_type);

        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            ZslOrder order = iZslOrderService.selectById(Long.parseLong(out_trade_no));
            if (order.getState() == 1) {
                //待付款订单
                order.setState(2);
                iZslOrderService.updateById(order);
                if (order.getType() == 1) {
                    //加盟平台
                    SysUser sysUser = iSysUserService.selectById(order.getUserId());
                    if (sysUser.getEmail() == null || sysUser.getEndTime().getTime() < System.currentTimeMillis()) {
                        sysUser.setEndTime(new Date());
                    }
                    if ("1".equals(order.getRemark())) {
                        sysUser.setEndTime(DateUtil.getSomeDay(sysUser.getEndTime(), 1));
                    } else {
                        sysUser.setEndTime(DateUtil.getSomeDay(sysUser.getEndTime(), 3));
                    }
                    iSysUserService.updateById(sysUser);
                }

            }

            return "success";
        } else {//验证失败
            return "fail";
        }


    }

}

